package com.tjec.project.projectWorkbench.controller;

import com.tjec.common.constant.Constants;
import com.tjec.common.utils.SecurityUtils;
import com.tjec.common.utils.StringUtils;
import com.tjec.framework.aspectj.lang.annotation.Log;
import com.tjec.framework.aspectj.lang.enums.BusinessType;
import com.tjec.framework.interceptor.annotation.RepeatSubmit;
import com.tjec.framework.web.controller.BaseController;
import com.tjec.framework.web.domain.AjaxResult;
import com.tjec.framework.web.domain.TreeSelect;
import com.tjec.framework.web.page.TableDataInfo;
import com.tjec.project.businessWorkbench.domain.BmsBusiness;
import com.tjec.project.businessWorkbench.domain.BmsBusinessDocArchive;
import com.tjec.project.businessWorkbench.domain.BmsProjectDocCatalog;
import com.tjec.project.businessWorkbench.mapper.BmsBusinessDocArchiveMapper;
import com.tjec.project.businessWorkbench.service.IBmsBusinessDocArchiveService;
import com.tjec.project.businessWorkbench.service.IBmsBusinessService;
import com.tjec.project.businessWorkbench.service.IBmsProjectDocCatalogService;
import com.tjec.project.projectWorkbench.domain.BmsProject;
import com.tjec.project.projectWorkbench.domain.BmsProjectContract;
import com.tjec.project.projectWorkbench.domain.BmsProjectMember;
import com.tjec.project.projectWorkbench.service.IBmsProjectMemberService;
import com.tjec.project.projectWorkbench.service.IBmsProjectService;
import com.tjec.project.projectWorkbench.service.impl.BmsReportNoServiceImpl;
import com.tjec.project.system.domain.BmsMdArchiveTemplate;
import com.tjec.project.system.domain.BmsMdBusinessCategory;
import com.tjec.project.system.domain.SysUser;
import com.tjec.project.system.domain.vo.BmsMdBusinessCategoryVO;
import com.tjec.project.system.service.IBmsMdArchiveTemplateService;
import com.tjec.project.system.service.IBmsMdBusinessCategoryService;
import com.tjec.project.system.service.ISysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 项目主页-业务管理Controller
 *
 * @author cjj
 * @date 2020-04-29
 */
@Api(value = "项目主页-业务管理" , tags = {"项目主页-业务管理接口"})
@RestController
@RequestMapping("/project/business")
public class BmsProjectBusinessController extends BaseController {

    @Autowired
    private IBmsBusinessService bmsBusinessService;

    @Autowired
    private IBmsBusinessDocArchiveService bmsBusinessDocArchiveService;

    @Autowired
    private IBmsProjectMemberService bmsProjectMemberService;

    @Autowired
    private IBmsMdBusinessCategoryService bmsMdBusinessCategoryService;

    @Autowired
    private IBmsMdArchiveTemplateService bmsMdArchiveTemplateService;

    @Autowired
    private IBmsProjectService bmsProjectService;

    @Autowired
    private ISysUserService sysUserService;
    
    @Autowired
    private BmsBusinessDocArchiveMapper bmsBusinessDocArchiveMapper;

    /**
     * 查询业务管理列表
     */
    @ApiOperation("业务管理列表分页")
//    @PreAuthorize("@ss.hasPermi('project:business:list')")
    @GetMapping("/list")
    public TableDataInfo list(BmsBusiness bmsBusiness)
    {
        if(StringUtils.isBlank(bmsBusiness.getProjectId())){
            return null;
        }
//        bmsBusiness.setUserId(SecurityUtils.getLoginUser().getUser().getUserId());
//        bmsBusiness.setTenderMemberFlag(bmsBusinessDocArchiveMapper.checkUserByProjectId(SecurityUtils.getLoginUser().getUser().getUserId(), bmsBusiness.getProjectId()));
        Set<String> engineeringBiddingList = bmsMdBusinessCategoryService.selectEngineeringBidding();
        startPage();
        List<BmsBusiness> list = bmsBusinessService.selectBmsBusinessList(bmsBusiness);
        for (BmsBusiness business : list) {
            if(bmsProjectMemberService.isTenderMembers(SecurityUtils.getLoginUser().getUser().getUserId(), business)
                    &&engineeringBiddingList.contains(business.getBusinessCategoryId())){
                business.setTenderMemberFlag("0");
            }else{
                business.setTenderMemberFlag("1");
            }
        }
        return getDataTable(list);
    }

    /**
     * 过滤当前登录人不是招标组长、组员并且为项目成员，业务中存在招标代理类业务
     * @param list
     * @param projectId
     */
    private List<BmsBusiness> filterList(List<BmsBusiness> list,String projectId){
//        boolean flag = bmsProjectMemberService.isTenderMember(SecurityUtils.getLoginUser().getUser().getUserId(), projectId);
        Set<String> engineeringBiddingList = bmsMdBusinessCategoryService.selectEngineeringBidding();
        list = list.stream().filter(business->!(bmsProjectMemberService.isTenderMembers(SecurityUtils.getLoginUser().getUser().getUserId(), business)&&engineeringBiddingList.contains(business.getBusinessCategoryId()))).collect(Collectors.toList());
        for (BmsBusiness business : list) {
            if(StringUtils.isNotBlank(business.getTenderMember())){
                String[] tenderMembers = business.getTenderMember().split(";");
                business.setTenderMembers(tenderMembers);
            }
        }
        return list;
    }

    /**
     * 是否为招标代理类业务
     */
    @ApiOperation("是否为招标代理类业务")
//    @PreAuthorize("@ss.hasPermi('project:business:list')")
    @GetMapping("/isEngineeringBidding/{businessCategoryId}")
    public AjaxResult isEngineeringBidding(@PathVariable String businessCategoryId)
    {
        boolean isEngineeringBidding = false;
        if(bmsMdBusinessCategoryService.selectEngineeringBidding().contains(businessCategoryId)){
            isEngineeringBidding = true;
        }
        return AjaxResult.success(isEngineeringBidding);
    }

    /**
     * 获取报告类型数量
     */
    @ApiOperation("获取报告类型数量")
//    @PreAuthorize("@ss.hasPermi('project:business:list')")
    @GetMapping("/getReportTypeCounts/{businessId}")
    public AjaxResult getReportTypeCounts(@PathVariable String businessId)
    {
        BmsBusiness bmsBusiness = bmsBusinessService.getReportTypeCounts(businessId);
        if(bmsBusiness == null){
            bmsBusiness = new BmsBusiness();
        }
        return AjaxResult.success(bmsBusiness);
    }

    /**
     *
     * @param treeSelects
     * @return
     */
    private Set<String> treeSelect(List<TreeSelect> treeSelects){
        Set<String> set = new HashSet<>();
        for (TreeSelect treeSelect : treeSelects) {
            set.add(treeSelect.getId());
            treeSelect(treeSelect.getChildren());
        }
        return set;
    }

    /**
     * 归档模板列表
     */
    @ApiOperation("归档模板列表")
//    @PreAuthorize("@ss.hasPermi('project:business:docArchiveList')")
    @GetMapping("/docArchiveList/{businessCategoryId}")
    public AjaxResult docArchiveList(@PathVariable("businessCategoryId") String businessCategoryId)
    {
        BmsMdArchiveTemplate bmsMdArchiveTemplate = new BmsMdArchiveTemplate();
        bmsMdArchiveTemplate.setBusinessCategoryId(businessCategoryId);
        List<BmsMdArchiveTemplate> list = bmsMdArchiveTemplateService.selectBmsMdArchiveTemplateList(bmsMdArchiveTemplate);
//        List<BmsBusinessDocArchive> list = bmsBusinessDocArchiveService.selectBmsBusinessDocArchiveListByProjectId(projectId);
        return AjaxResult.success(list);
    }

    /**
     * 新增业务管理
     */
    @Transactional
    @ApiOperation("新增业务管理")
    @ApiImplicitParam(name = "bmsBusiness", value = "新增业务管理", dataType = "BmsBusiness")
    @Log(title = "业务管理", businessType = BusinessType.INSERT)
//    @PreAuthorize("@ss.hasPermi('project:business:add')")
    @RepeatSubmit
    @PostMapping
    public AjaxResult add(@RequestBody BmsBusiness bmsBusiness)
    {
        if(null==bmsBusiness.getProjectId()){
            return AjaxResult.error("请添加项目Id字段：projectId");
        }else{
            return  AjaxResult.success(bmsBusinessService.insertBmsBusiness(bmsBusiness));
        }
    }

    /**
     * 编辑业务管理
     */
    @ApiOperation("编辑业务管理")
    @ApiImplicitParam(name = "bmsBusiness", value = "编辑业务管理", dataType = "BmsBusiness")
    @Log(title = "业务管理", businessType = BusinessType.UPDATE)
//    @PreAuthorize("@ss.hasPermi('project:business:edit')")
    @PutMapping
    public AjaxResult edit(@RequestBody BmsBusiness bmsBusiness)
    {
        return toAjax(bmsBusinessService.updateBmsBusiness(bmsBusiness));
    }

    /**
     * 获取业务管理详细信息
     */
    @ApiImplicitParam(name = "guid", value = "业务guid", required = true, dataType = "String", paramType = "path")
//    @PreAuthorize("@ss.hasPermi('project:business:query')")
    @GetMapping(value = "/{guid}")
    public AjaxResult getInfo(@PathVariable("guid") String guid)
    {
        return AjaxResult.success(bmsBusinessService.selectBmsBusinessByGuid(guid));
    }

    /**
     * 业务迁移查询
     */
    @ApiOperation("业务迁移查询")
    @ApiImplicitParam(name = "bmsBusiness", value = "业务迁移查询", dataType = "BmsBusiness")
//    @PreAuthorize("@ss.hasPermi('project:business:migrationList')")
    @GetMapping(value = "/migrationList")
    public AjaxResult migrationList(BmsProject bmsProject)
    {
        bmsProject.setIsvalid("1");
        List<BmsProject> list = bmsProjectService.selectBmsProjectList(bmsProject);
        if(CollectionUtils.isEmpty(list)) {
            return AjaxResult.error("未找到对应项目，请核实项目代码是否正确");
        }
        if(list.get(0).getEnableFlag().equals("1")){
            return AjaxResult.error("项目未启用，请联系该项目的项目负责人，启用项目后再进行业务迁移操作");
        }
        return AjaxResult.success(list);
    }
    /**
     * 业务迁移
     */
    @ApiOperation("业务迁移")
    @ApiImplicitParam(name = "bmsBusiness", value = "编辑业务管理", dataType = "BmsBusiness")
//    @PreAuthorize("@ss.hasPermi('project:business:migration')")
    @PutMapping(value = "/migration")
    public AjaxResult migration(@RequestBody BmsBusiness bmsBusiness)
    {
        if(StringUtils.isNoneBlank(bmsBusiness.getProjectId(), bmsBusiness.getGuid())){
            return toAjax(bmsBusinessService.migrationBmsBusiness(bmsBusiness));
        }else{
            return AjaxResult.error("项目id、迁移项目id、业务id不能为空");
        }
    }

    /**
     * 查询项目成员列表
     */
    @ApiOperation("招标组组长和组员选择列表")
//    @PreAuthorize("@ss.hasPermi('project:member:list')")
    @GetMapping("/tenderList")
    public AjaxResult tenderList(BmsProjectMember bmsProjectMember)
    {
        List<BmsProjectMember> list = bmsProjectMemberService.selectBmsProjectMemberList(bmsProjectMember);
        SysUser sysUser = sysUserService.findSysuUserByProjectLeaderNo(bmsProjectService.selectBmsProjectByGuid(bmsProjectMember.getProjectId()).getProjectLeaderNo());
        if(sysUser!=null){
            BmsProjectMember projectMember = new BmsProjectMember();
            projectMember.setUserId(sysUser.getUserId());
            projectMember.setNickName(sysUser.getNickName());
            List<String> userIds= list.stream().map(e -> e.getUserId()).collect(Collectors.toList());
            if(!userIds.contains(sysUser.getUserId())){
                list.add(projectMember);
            }
        }
        return AjaxResult.success(list);
    }
    
    /**
     * 业务管理列表，只取没有咨询报告号的
     */
    @ApiOperation("业务管理列表，只取没有咨询报告号的")
//    @PreAuthorize("@ss.hasPermi('project:business:list')")
    @GetMapping("/noReportNoList")
    public AjaxResult noReportNoList(BmsBusiness bmsBusiness)
    {
        if(StringUtils.isBlank(bmsBusiness.getProjectId())){
            return null;
        }
//        boolean flag = bmsProjectMemberService.isTenderMembers(SecurityUtils.getLoginUser().getUser().getUserId(), bmsBusiness.getProjectId());
        List<BmsBusiness> list = bmsBusinessService.selectBusinessNoReportNoList(bmsBusiness);
        return AjaxResult.success(list);
    }
    
    /**
     * 业务管理列表，只取没有招标代理号的
     */
    @ApiOperation("业务管理列表，只取没有招标代理号的")
    @GetMapping("/noAgencyNoList")
    public AjaxResult noAgencyNoList(BmsBusiness bmsBusiness)
    {
        if(StringUtils.isBlank(bmsBusiness.getProjectId())){
            return null;
        }
        
        /*
        boolean flag = bmsProjectMemberService.isTenderMember(SecurityUtils.getLoginUser().getUser().getUserId(), bmsBusiness.getProjectId());
        List<BmsBusiness> list = bmsBusinessService.selectBusinessNoAgencyNoList(bmsBusiness);
        Set<String> engineeringBiddingList = bmsMdBusinessCategoryService.selectEngineeringBidding();
        //过滤当前登录人不是招标组长、组员并且为项目成员，业务中存在招标代理类业务
        list = list.stream().filter(business->(!flag&&engineeringBiddingList.contains(business.getBusinessCategoryId()))).collect(Collectors.toList());
        for (BmsBusiness business : list) {
            if(StringUtils.isNotBlank(business.getTenderMember())){
                String[] tenderMembers = business.getTenderMember().split(";");
                business.setTenderMembers(tenderMembers);
            }
        }
        */
        
        
        List<BmsBusiness> list = bmsBusinessService.selectBusinessNoAgencyNoList(bmsBusiness);
        
      //先判断当前登陆人是否是项目负责人或项目经理
        String res = bmsBusinessDocArchiveMapper.checkUserByProjectId(SecurityUtils.getLoginUser().getUser().getUserId(), bmsBusiness.getProjectId());
        //如果是项目负责人或项目经理
        if("1".equals(res)) {
        	return AjaxResult.success(list);
        }else {
        	if(list!=null && list.size()>0) {
        		 List<BmsBusiness> resList = new ArrayList<BmsBusiness>();
        		 String userId = SecurityUtils.getLoginUser().getUser().getUserId();
        		 for (BmsBusiness item : list) {
        			 if(item.getTenderLeader().indexOf(userId)>=0 || item.getTenderMember().indexOf(userId)>=0) {
        				 resList.add(item);
        			 }
				}
        		 return AjaxResult.success(resList);
        	}else {
        		return AjaxResult.success(list);
        	}
        }
    }
    
    /**
     * 业务管理列表，只取没有造价报告号的
     */
    @ApiOperation("业务管理列表，只取没有造价报告号的")
//    @PreAuthorize("@ss.hasPermi('project:business:list')")
    @GetMapping("/noCostNoList")
    public AjaxResult noCostNoList(BmsBusiness bmsBusiness)
    {
        if(StringUtils.isBlank(bmsBusiness.getProjectId())){
            return null;
        }
        List<BmsBusiness> list = bmsBusinessService.selectBusinessNoCostNoList(bmsBusiness);
        return AjaxResult.success(list);
    }
    
    @ApiOperation("获取业务类别")
    @GetMapping("/getServiceBussinessTypes/{projectId}")
    public AjaxResult getBusinessTypes(@PathVariable("projectId") String projectId) {
    	List<BmsMdBusinessCategoryVO> businessTypes = bmsBusinessService.selectBusinessTypes(projectId);
    	return AjaxResult.success(bmsMdBusinessCategoryService.buildBusinessTreeSelectNew(businessTypes));
    }
    
    @ApiOperation("判断本项目是否包含该业务类别")
    @GetMapping("/checkProject/{projectId}/{businessId}")
    public AjaxResult checkProject(@PathVariable("projectId") String projectId,@PathVariable("businessId") String businessId) {
    	return AjaxResult.success(bmsBusinessService.checkProject(projectId,businessId));
    }
    
    @ApiOperation("判断本业务是否能发起流程")
    @GetMapping("/checkBusiness/{projectId}/{businessTypeId}")
    public AjaxResult checkBusiness(@PathVariable("businessTypeId") String businessTypeId,@PathVariable("projectId")String projectId) {
    	return AjaxResult.success(bmsBusinessService.checkBusiness(projectId,businessTypeId));
    }
    
    @ApiOperation("检查本项目下业务名称是否重复")
    @GetMapping("/checkBussinessNameSingle")
    public AjaxResult checkBussinessNameSingle(BmsBusiness bmsBusiness) {
    	return AjaxResult.success(bmsBusinessService.checkBussinessNameSingle(bmsBusiness));
    }
    
    @ApiOperation("获取本业务类别下的报告类型")
    @GetMapping("/getReportType/{businessTypeId}")
    public AjaxResult getReportType(@PathVariable("businessTypeId") String businessTypeId) {
    	return AjaxResult.success(bmsBusinessService.getReportType(businessTypeId));
    }

    @ApiOperation("获取新项目信息和原项目信息")
    @ApiImplicitParam(name = "bmsBusiness", value = "获取新项目信息和原项目信息", dataType = "BmsBusiness")
    @GetMapping(value = "/getNewAndOldProjectInfo/{newProjectId}/{oldProjectId}/{businessId}")
    public AjaxResult getNewAndOldProjectInfo(@PathVariable("newProjectId") String newProjectId,@PathVariable("oldProjectId") String oldProjectId,@PathVariable("businessId") String businessId)
    {
        if(StringUtils.isNotBlank(newProjectId) && StringUtils.isNotBlank(oldProjectId) && StringUtils.isNotBlank(businessId)){
            return AjaxResult.success(bmsBusinessService.selectNewAndOldProjectInfo(newProjectId,oldProjectId,businessId));
        }else{
            return AjaxResult.error("项目id不能为空");
        }
    }
    
    /**
     *作废业务
     */
    @ApiOperation("作废业务")
    @ApiImplicitParam(name = "bmsBusiness", value = "作废业务", dataType = "BmsBusiness")
    @Log(title = "业务管理", businessType = BusinessType.UPDATE)
    @PostMapping(value = "/cancelBusiness")
    public AjaxResult cancelBusiness(@RequestBody BmsBusiness bmsBusiness)
    {
        return toAjax(bmsBusinessService.cancelBusiness(bmsBusiness));
    }
    
    /**
     * 判断本业务是否有成果盖章流程
     */
    @ApiOperation("判断本业务是否有成果盖章流程")
    @ApiImplicitParam(name = "bmsBusiness", value = "作废业务", dataType = "BmsBusiness")
    @Log(title = "业务管理", businessType = BusinessType.UPDATE)
    @PostMapping(value = "/checkWorkflow")
    public AjaxResult checkWorkflow(@RequestBody BmsBusiness bmsBusiness)
    {
        return AjaxResult.success((bmsBusinessService.checkWorkflow(bmsBusiness)));
    }
    
    @ApiOperation("取消本业务下的进行中流程")
    @ApiImplicitParam(name = "bmsBusiness", value = "取消本业务下的进行中流程", dataType = "BmsBusiness")
    @GetMapping(value = "/cancelInstance/{businessId}")
    public AjaxResult cancelInstance(@PathVariable("businessId") String businessId)
    {
    	bmsBusinessService.cancelInstance(businessId);
    	return AjaxResult.success();
    }
    
}
